package com.spring.sunflower.conversation

import android.view.WindowManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshListener
import com.spring.sunflower.R
import com.spring.sunflower.base.BaseCompatActivity
import com.spring.sunflower.bean.MessageCustomEntity
import com.spring.sunflower.constant.Constant
import com.tencent.imsdk.v2.V2TIMManager
import com.tencent.imsdk.v2.V2TIMMessage
import com.tencent.imsdk.v2.V2TIMMessageListGetOption
import com.tencent.imsdk.v2.V2TIMValueCallback
import org.greenrobot.eventbus.Subscribe
import java.util.*

/**
 * Created by Kevin on 2021/8/9<br/>
 *
 * Describe:<br/>
 */
class SystemNoticeActivity : BaseCompatActivity(), OnRefreshListener {
    private var refreshLayout: SmartRefreshLayout? = null
    private var mRecyclerView: RecyclerView? = null
    private var mOtherShowName: String? = null
    private var mOtherFaceUrl: String? = null
    private var mSelfUserID: String? = null
    private var mSelfAvatar: String? = null
    private var mSelfNickname: String? = null
    private val messageList: MutableList<MessageCustomEntity> = ArrayList()
    private var mAdapter: ChatCustomSystemAdapter? = null
    private val msgCount = 20
    private var lastV2TIMMessage: V2TIMMessage? = null
    private val messageListTemp: MutableList<MessageCustomEntity> = ArrayList()
    private val mOtherUserID = "10000"
    override fun doSomethingBeforeOnCreate() {
        super.doSomethingBeforeOnCreate()
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
    }

    override fun getLayoutID(): Int = R.layout.activity_system_notice
    override fun initView() {
        tvTitle.text = "系统通知"
        val intent = intent
        val conversationId = intent.getStringExtra(Constant.C2C_CONVERSATION_ID)
        mOtherShowName = intent.getStringExtra(Constant.C2C_SHOW_NAME)
        mOtherFaceUrl = intent.getStringExtra(Constant.C2C_FACE_URL)
        mSelfUserID = getField(Constant.KEY_USERID, "")
        mSelfAvatar = getField(Constant.KEY_PHOTO, "")
        mSelfNickname = getField(Constant.KEY_NICKNAME, "")
        saveField(Constant.KEY_USERID_CHATTER, mOtherUserID)
        saveField(Constant.KEY_AVATAR_CHATTER, mOtherFaceUrl)
        saveField(Constant.KEY_NICKNAME_CHATTER, mOtherShowName)
        refreshLayout = findViewById(R.id.refreshLayout)
        mRecyclerView = findViewById(R.id.rvRecyclerView)
        refreshLayout?.setEnableLoadMore(false)
        val layoutManager = LinearLayoutManager(this)
        mRecyclerView?.layoutManager = layoutManager
        mAdapter = ChatCustomSystemAdapter(messageList)
        mRecyclerView?.adapter = mAdapter
        getMsgHistory(null)
        refreshLayout?.setOnRefreshListener(this)
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        getMsgHistory(lastV2TIMMessage)
    }

    private fun getMsgHistory(lastMsg: V2TIMMessage?) {
        android.os.Handler().postDelayed({
            if (refreshLayout!!.isRefreshing) {
                refreshLayout!!.finishRefresh()
            }
        }, 2500)
        val v2TIMMessageListGetOption = V2TIMMessageListGetOption()
        v2TIMMessageListGetOption.count = msgCount
        v2TIMMessageListGetOption.lastMsg = lastMsg
        v2TIMMessageListGetOption.userID = mOtherUserID
        V2TIMManager.getMessageManager().getC2CHistoryMessageList(
            mOtherUserID,
            msgCount,
            lastMsg,
            object : V2TIMValueCallback<List<V2TIMMessage>> {
                override fun onError(i: Int, s: String) {
                    if (refreshLayout!!.isRefreshing) {
                        refreshLayout!!.finishRefresh()
                    }
                    showToast("获取失败code:$i,msg=$s")
                }

                override fun onSuccess(v2TIMMessages: List<V2TIMMessage>) {
                    if (v2TIMMessages.size > 0) {
                        lastV2TIMMessage = v2TIMMessages[v2TIMMessages.size - 1]
                        val messageEntities: List<MessageCustomEntity> =
                            processMessageList(v2TIMMessages)
                        if (mAdapter == null) {
                            printE("mAdapter is null")
                        } else {
                            printE("mAdapter is not null")
                        }
                        mAdapter?.addData(0, messageEntities)
                        if (lastMsg == null) {
                            mRecyclerView?.scrollToPosition(mAdapter!!.itemCount - 1)
                        }
                        if (refreshLayout!!.isRefreshing) {
                            refreshLayout!!.finishRefresh()
                        }
                    }
                }
            })
    }

    private fun processMessageList(v2TIMMessages: List<V2TIMMessage?>): List<MessageCustomEntity> {
        messageListTemp.clear()
        Collections.reverse(v2TIMMessages)
        for (v in v2TIMMessages) {
            val bean = ConversationManager.processV2TIMMessage(v)
            if (bean != null) {
                val messageCustomEntity =
                    ConversationManager.customMessageBean2MessageCustomEntity(bean, v)
                messageListTemp.add(messageCustomEntity)
            }
        }
        return messageListTemp
    }

    override fun shouldRegisterEventBus(): Boolean {
        return true
    }

    @Subscribe
    fun refreshMsg(message: V2TIMMessage) {
        printD("msg=$message")
        //收到消息判断当前时间和之前的时间差大于5分钟就添加时间显示
        if (ConversationManager.shouldInsertTime()) {
            val msg: MutableList<V2TIMMessage> = ArrayList()
            ConversationManager.insertLocalMessage(
                Constant.CUSTOM_MESSAGE_LOCAL_TIME,
                false,
                object : V2TIMValueCallback<V2TIMMessage> {
                    override fun onSuccess(v2TIMMessage: V2TIMMessage) {
                        msg.add(v2TIMMessage)
                        msg.add(message)
                        refreshChatList(msg, false)

                    }

                    override fun onError(code: Int, desc: String) {
                        printD("ErrorCode=$code,desc=$desc")
                    }
                })
        } else {
            refreshChatList(message, false)
        }
    }

    fun refreshChatList(msg: List<V2TIMMessage?>, isSend: Boolean) {
//        MessageEntity messageEntity = V2TIMMessageConvertToMessageEntity(msg);
        val messageCustomEntityList: MutableList<MessageCustomEntity> = ArrayList()
        for (message in msg) {
            val bean = ConversationManager.processV2TIMMessage(message)
            if (isSend) {
                val messageCustomEntity =
                    ConversationManager.customMessageBean2MessageCustomEntity(bean, message)
                if (messageCustomEntity != null) {
                    messageCustomEntityList.add(messageCustomEntity)
                }
            } else {
                if (bean != null) {
                    if (bean.data != null) {
                        if (bean.data.fromUser.memberId == mOtherUserID || bean.data.msgType == Constant.CUSTOM_MESSAGE_LOCAL_TIME) {
                            val messageCustomEntity =
                                ConversationManager.customMessageBean2MessageCustomEntity(
                                    bean,
                                    message
                                )
                            if (messageCustomEntity != null) {
                                messageCustomEntityList.add(messageCustomEntity)
                            }
                        } else {
                        }
                    }
                }
            }
        }
        mAdapter!!.addData(messageCustomEntityList)
        scrollToEnd()
    }

    private fun refreshChatList(msg: V2TIMMessage?, isSend: Boolean) {
//        MessageEntity messageEntity = V2TIMMessageConvertToMessageEntity(msg);
        val bean = ConversationManager.processV2TIMMessage(msg)
        if (isSend) {
            val messageCustomEntity =
                ConversationManager.customMessageBean2MessageCustomEntity(bean, msg)
            if (messageCustomEntity != null) {
                mAdapter!!.addData(messageCustomEntity)
                scrollToEnd()
            }
        } else {
            if (bean != null) {
                if (bean.data != null) {
                    if (bean.data.fromUser.memberId == mOtherUserID) {
                        val messageCustomEntity =
                            ConversationManager.customMessageBean2MessageCustomEntity(bean, msg)
                        if (messageCustomEntity != null) {
                            mAdapter!!.addData(messageCustomEntity)
                            scrollToEnd()
                        }
                    } else {
                    }
                }
            }
        }
    }

    private fun scrollToEnd() {
        mRecyclerView?.scrollToPosition(mAdapter!!.itemCount - 1)
    }
}